<template>
  <div class="container_warp">
    <div class="search_wrap test-harry">
      <d-search v-model="search" icon-position="left" :placeholder="$t('news.searchPlaceholder')"
        @keypress.enter="handleConfirm" />
      <div />
      <!-- 轮播图 -->
      <div class="swiper_news_wrap" :key="resetId">
        <div class="swiper_wrap">
          <!-- <DCarousel :autoplay="true"> <DCarouselItem v-for="item in recentlyUpdateList" :key="item.id"> <GLink :href="`/news/${item.id}`" target="_blank"> <img :key="item.coverImg" class="cover_img" :src="item.coverImg"> </GLink> </DCarouselItem> </DCarousel> -->
          <CustomSwiper class="banner-news" :data="recentlyUpdateList" controls @slide-click="handleSlideClick" />
        </div>
        <!-- <div class="news_wrap" v-show="recentlyUpdateList.length">  <div class="title mb-[.5rem]">    {{ $t('news.recentUpdate') }}  </div>  <div v-for="item in recentlyUpdateList" :key="item.id" class="news_list mb-[.5rem]">    <GLink :href="`/news/${item.id}`" target="_blank">      <News :data="item" />    </GLink>  </div></div> -->
      </div>
      <!-- 资讯专栏 -->
      <div class="special_column_wrap">
        <!-- <div class="special_list"> <span v-for="(item, index) in specialList" :key="item.key" :style="{ color: specialIndex === index ? '#242536' : '#9C9DB4' }" @click="handlerType(item, index)">{{ item.label }}</span> </div> -->

        <div class="card_list_wrap">
          <div v-for="item in newsList" :key="item.id" class="list_child" :span="6">
            <GLink :to="`/news/${item.id}`" target="_blank">
              <Card :data="item" />
            </GLink>
          </div>
        </div>
        <p class="tips" v-show="newsList.length">{{ $t('news.noMore') }}</p>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { Carousel as DCarousel, CarouselItem as DCarouselItem } from 'vue-devui/carousel'
import News from './components/News.vue'
import Card from './components/Card.vue'
import CustomSwiper from '@/components/CustomSwiper/index.vue'
import type { IResult } from './types/index'
import allNewsData from '../Data/news.json'
import { NEWS_SORT } from '../Doc/sort'
import { useI18n } from 'vue-i18n';
import dayjs from 'dayjs'
import { useMenuData } from '~/composables/hooks/useMenuData.ts'
import { onBeforeRouteUpdate } from 'vue-router'
import { keepAliveComponentName } from '@/constant';
const { t } = useI18n()
// 获取cookie里参数
const lan = useCookie('lang').value || 'zh';
const newsData = allNewsData[lan] || allNewsData.zh;
const sortList = NEWS_SORT[lan];
const newsList = ref<Array<IResult>>([]) // 每个专栏的文章列表
const recentlyUpdateList = ref<Array<IResult>>([]) // 最近更新的文章列表
const search = ref('') // 搜索参数
const recentlyUpdateIdsList = ref<Array<string>>([]) // 最近更新列表的id组合
const allContentList = ref<Array<IResult>>([]) // 所有的文章集合
const resetId = ref(0)
const router = useRouter()
const { newMenu: menus, defaultNav } = useMenuData()
function handleSlideClick({ slide, index }: { slide: any, index: number }) {
  const url = router.resolve({ name: 'news-detail', params: { id: slide.id } })
  window.open(url.href, '_blank');
}

// 获取专栏列表
function getSpecialTypeList() {
  allContentList.value = Object.values(newsData).flat() // 获取所有的文章列表
  getArticleListData()
}

// 获取每个专栏的文章列表,并还要排除掉最近更新的文章
function getSubList(keyword:string) {
  newsList.value = sortTime(newsData[keyword].filter((res: IResult) => !recentlyUpdateIdsList.value.includes(res.id)))
}

//按时间排序
function sortTime(list:Array<IResult>) {
  if (Array.isArray(list) && list.length) {
    return list.sort((a, b) => {
      return dayjs(a.releaseTime).isAfter(dayjs(b.releaseTime)) ? -1 : 1;
    });
  } {
    return []
  }

}

/**
 * 获取轮播图数据
 * banner固定为4个，根据类型取，支持运营手动配置，如果运营手动配置不够4个，剩下的按照时间取全部中最新的进行补齐到4个
 */
function getCarouselData(label: string) {
  const carouselList = newsList.value.filter((res) => res?.isBanner).slice(0, 4) 
  const allList = sortTime(allContentList.value)
  //当前栏目没有4篇banner，则从当前栏目中获取最新的
  if (carouselList.length < 4) {
    carouselList.push(...newsList.value.filter((res) => (!carouselList.find((item) => item.id === res.id))).slice(0, 4 - carouselList.length))
  }

  // 还不够4篇，则从所有栏目中获取最新的
  // if(carouselList.length < 4) {
  //   carouselList.push(...allList.filter((res) => !carouselList.find((item) => item.id === res.id)).slice(0, 4 - carouselList.length))
  // }

  recentlyUpdateList.value = carouselList
  resetId.value = Date.now()
}

// 获取所有的文章列表包括未被收录的,并还要排除掉最近更新的文章
function getArticleListData() {
  
  //展示对应专栏的文章
  const key = menus.value.find(item => item.key === defaultNav.value)?.label
  getSubList(key)
  getCarouselData(key)
}

// 跳转到搜索页面
function handleConfirm() {
  navigateTo({
    name: 'search',
    query: {
      search: search.value,
      tab: 'article',
      nav: defaultNav.value
    }
  })
}

useSeoMeta({
  charset: 'utf-8',
  title: () => t('news.tdk.title'),
  ogTitle: () => t('news.tdk.title'),
  description: () => t('news.tdk.desc'),
  ogDescription: () => t('news.tdk.desc'),
  keywords: () => t('news.tdk.keyword'),
  ogKeywords: () => t('news.tdk.keyword'),
})

getSpecialTypeList()

/** 
 * 菜单切换时重新获取轮播图数据，并重新获取专栏列表，并滚动到顶部 
 **/
function handleRouteUpdate(nav: string) {
  const label = menus.value.find(item => item.key === nav)?.label
  // 菜单切换时重新获取轮播图数据，并重新获取专栏列表，并滚动到顶部
  getSubList(label)
  getCarouselData(label)
  scrollTo(0, 0)
}

onBeforeRouteUpdate((to, from, next) => {
  // 路由变化时刷新数据
  const nav = to.query.nav
  defaultNav.value = nav
  handleRouteUpdate(nav)
  next()
})

onActivated(() => {
  // 组件激活时刷新数据，防止路由变化时数据不刷新
  const nav = router.currentRoute.value.query.nav
  if(nav && nav !== defaultNav.value) {
    defaultNav.value = nav
    handleRouteUpdate(nav)
  }
})

defineOptions({
  name: keepAliveComponentName.News
})

</script>

<style lang="scss" scoped>
$repair-width-md: 102px;
$repair-width-lg: 142px;
$repair-width-xl: 192px;

// 新增一个mixin来处理slider-items-2的通用样式
@mixin slider-items-2-style {
  margin-left: 0;
  margin-right: 0;
}

@mixin slider-items-2-prev {
  &.slider-items-2 {
    margin-right: -50%;
    margin-left: 50%;
  }
}

@mixin slider-items-2-next {
  &.slider-items-2 {
    margin-left: -50%;
    margin-right: 50%;
  }
}

.container_warp {

  .search_wrap {
    width: 100%;
    margin: 0 auto 20px;
  }

  .swiper_news_wrap {
    margin: 20px auto;
    display: flex;
    align-items: center;
  }

  .swiper_wrap {
    flex: 1;

    :deep(.devui-carousel__item-wrapper) {
      border-radius: 4px;
    }
    .banner-news {
      @media (max-width: 768px) {
        :deep(.slider__slide.active .box) {
          margin-right: -$repair-width-md; 
          margin-left: -$repair-width-md;
          &.slider-items-2 {
            margin-right: -$repair-width-md * 0.6;
            margin-left: -$repair-width-md * 0.6;
          }
        }
        :deep(.slider__slide.prev .box) {
          margin-right: -$repair-width-md * 2;
          &.slider-items-2 { @include slider-items-2-prev; }
        }
        :deep(.slider__slide.next .box) {
          margin-left: -$repair-width-md * 2;
          &.slider-items-2 { @include slider-items-2-next; }
        }
      }
      @media (min-width: 1024px) {
        :deep(.slider__slide.active .box) {
          margin-left: -$repair-width-lg;
          margin-right: -$repair-width-lg;
          &.slider-items-2 { @include slider-items-2-style; }
        }
        :deep(.slider__slide.prev .box) {
          margin-right: -$repair-width-lg * 2;
          &.slider-items-2 { @include slider-items-2-prev; }
        }
        :deep(.slider__slide.next .box) {
          margin-left: -$repair-width-lg * 2;
          &.slider-items-2 { @include slider-items-2-next; }
        }
      }
      @media (min-width: 1280px) {
        :deep(.slider__slide.active .box) {
          margin-left: -$repair-width-xl;
          margin-right: -$repair-width-xl;
          &.slider-items-2 { @include slider-items-2-style; }
        }
        :deep(.slider__slide.prev .box) {
          margin-right: -$repair-width-xl * 2;
          &.slider-items-2 { @include slider-items-2-prev; }
        }
        :deep(.slider__slide.next .box) {
          margin-left: -$repair-width-xl * 2;
          &.slider-items-2 { @include slider-items-2-next; }
        }
      }
      :deep(.slider:not(.hydrated) .slider__slide:nth-child(2) .box) {
        @media (max-width: 768px) {
          margin-left: -$repair-width-md;
          margin-right: -$repair-width-md;
          &.slider-items-2 { @include slider-items-2-style; }
        }
        @media (min-width: 1024px) {
          margin-left: -$repair-width-lg;
          margin-right: -$repair-width-lg;
          &.slider-items-2 { @include slider-items-2-style; }
        }
        @media (min-width: 1280px) {
          margin-left: -$repair-width-xl;
          margin-right: -$repair-width-xl;
          &.slider-items-2 { @include slider-items-2-style; }
        }
      }
    }
  }

  .news_wrap {
    padding: 8px;
    border-radius: 4px;
    height: 100%;
    border: 1px solid #E3E3EE;
    flex: 0 0 300px;
    margin-left: 16px;
    overflow: hidden;
    min-height: 370px;

    .title {
      font-size: 16px;
      color: #3B3E55;
      font-weight: 600;
      padding: 12px 8px;
      background-color: #F9F9FB;
    }
  }
}

.special_list {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  padding-bottom: 16px;
  border-bottom: 1px solid #F1F1F8;

  span {
    font-size: 16px;
    font-weight: 600;
    color: #242536;
    padding-right: 32px;
    cursor: pointer;
  }
}

.card_list_wrap {
  margin-top: 16px;
  display: grid;
  gap: 16px;
}

.special_column_wrap {
  .tips {
    font-size: 14px;
    color: #9C9DB4;
    padding: 20px 0;
    text-align: center;
  }
}

.cover_img {
  object-fit: cover;
  height: 366px;
  width: 100%;
  border-radius: 4px;
}


@media screen and (max-width: 1280px) {
  .news_wrap {
    display: none;
  }

  .swiper_wrap .devui-carousel {
    height: 100%;
  }
}


@media screen and (max-width: 768px) {
  .cover_img {
    border-radius: 5px;
    height: 148px;
  }

  .card_list_wrap {
    @apply grid-cols-2
  }
}

@media screen and (min-width: 768px) {
  .swiper_wrap .devui-carousel {
    height: 366px !important;
  }

  .card_list_wrap {
    @apply grid-cols-4
  }
}

@media screen and (max-width: 1536px) {
  .card_list_wrap {
    @apply grid-cols-3
  }
}


@media screen and (max-width: 1280px) {
  .card_list_wrap {
    @apply grid-cols-2
  }
}

@media screen and (max-width: 768px) {
  .card_list_wrap {
    @apply grid-cols-1
  }
}

</style>
